import logging
import time
import allure
from appium import webdriver
from appium.webdriver import WebElement
from appium.webdriver.webdriver import WebDriver
from typing import List

"""
基类
"""


class Base:

    def __init__(self, driver_base: WebDriver = None):

        if not driver_base:

            logging.info("实例化driver对象")

            caps = dict()
            caps['platformName'] = "android"
            caps['appPackage'] = "com.tencent.wework"
            caps['appActivity'] = ".launch.LaunchSplashActivity"
            caps['noReset'] = "true"
            caps['deviceName'] = "Cliff"

            self.driver = webdriver.Remote("http://localhost:4723/wd/hub", caps)
            self.driver.implicitly_wait(5)

        else:
            self.driver = driver_base

    def find(self, by, locator) -> WebElement:
        """
        获取单个元素
        :param by:定位方式
        :param locator:表达式
        :return:
        """
        return self.driver.find_element(by, locator)

    def finds(self, by, locator) -> List[WebElement]:
        """
        获取一组元素
        :param by:定位方式
        :param locator:表达式
        :return:
        """
        return self.driver.find_elements(by, locator)

    def find_and_click(self, by, locator) -> WebElement:
        """
        获取并点击元素
        :param by:定位方式
        :param locator:表达式
        :return:
        """
        element = self.driver.find_element(by, locator)
        element.click()
        return element

    def do_screenshot(self, desc: str):
        timestamp = int(time.time())
        self.driver.save_screenshot(f"../pics/screenshot_{timestamp}.png")
        allure.attach.file(f"../pics/screenshot_{timestamp}.png", name=desc, attachment_type=allure.attachment_type.PNG)

    def close_driver(self):
        self.driver.close()
